package xcmg.device.service.ratingManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.ratingManager.MarketDealerRatingDO;
import xcmg.device.dao.entity.ratingManager.MarketDealerRatingDetailDO;
import xcmg.device.dao.entity.ratingManager.RuleStrategyRelationDO;
import xcmg.device.dao.entity.ratingManager.ScoreInfoDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.ratingManager.MarketDealerRatingDetailMapper;
import xcmg.device.dao.mapper.ratingManager.MarketDealerRatingMapper;
import xcmg.device.dao.mapper.ratingManager.RuleStrategyRelationDOMapper;
import xcmg.device.dao.mapper.ratingManager.ScoreInfoDOMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.marketing.MarketingActivityPriceVO;
import xcmg.device.service.vo.marketing.MarketingActivityVO;
import xcmg.device.service.vo.ratingManager.MarketingDealerRatingAddVO;
import xcmg.device.service.vo.ratingManager.MarketingDealerRatingVO;
import yb.ecp.fast.feign.FastGenClient;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2019/7/15.
 */
@Service
public class MarketDealerRatingService {
    @Autowired
    private MarketDealerRatingMapper marketDealerRatingMapper;
    @Autowired
    private MarketDealerRatingDetailMapper marketDealerRatingDetailMapper;
    @Autowired
    private FastGenClient genClient;
    @Autowired
    private ScoreInfoDOMapper scoreInfoDOMapper;
    @Autowired
    private CompanyDealerMapper companyDealerMapper;
    @Autowired
    private PriMaterialsMapper priMaterialsMapper;
    @Autowired
    private RuleStrategyRelationDOMapper ruleStrategyRelationDOMapper;

    public ErrorCode add(MarketingDealerRatingAddVO addVO, String orgId) throws Exception {
        List<MarketingDealerRatingVO> marketingDealerList = addVO.getMarketingDealerList();
        String ratingId = addVO.getRatingId();
        List<MarketDealerRatingDetailDO> insertDOList = new ArrayList<>();
        for (MarketingDealerRatingVO marketingDealerRatingVO : marketingDealerList) {
            String mainId = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(mainId)) {
                throw new Exception("主键生成失败");
            }
            Integer endRanking = marketingDealerRatingVO.getEndRanking();
            Integer startRanking = marketingDealerRatingVO.getStartRanking();
            String grad = marketingDealerRatingVO.getLevel();
            scoreInfoDOMapper.updateByrRatingIdRanking(ratingId, startRanking, endRanking, grad);
            List<ScoreInfoDO> scoreInfoDOList = scoreInfoDOMapper.selectByRatingIdRanking(ratingId, startRanking, endRanking);
            getMarketDealerRatingDetailDO(insertDOList, marketingDealerRatingVO, mainId, scoreInfoDOList);
            MarketDealerRatingDO record = new MarketDealerRatingDO();
            record.setId(mainId);
            record.setRatingId(ratingId);
            record.setCreateDate(new Date());
            record.setEffectiveDate(marketingDealerRatingVO.getEffectiveDate());
            record.setEndRanking(endRanking);
            record.setFailureDate(marketingDealerRatingVO.getFailureDate());
            record.setGrad(grad);
            record.setOrgId(orgId);
            record.setStartRanking(startRanking);
            boolean success = marketDealerRatingMapper.insertSelective(record) > 0;
            if (success) {
                marketDealerRatingDetailMapper.batchInsert(insertDOList);
            }
        }
        return ErrorCode.Success;
    }

    public ErrorCode addOrUpdate(MarketingDealerRatingAddVO addVO, String orgId) throws Exception {
        List<MarketingDealerRatingVO> marketingDealerList = addVO.getMarketingDealerList();
        String ratingId = addVO.getRatingId();
        for (MarketingDealerRatingVO marketingDealerRatingVO : marketingDealerList) {
            List<MarketDealerRatingDetailDO> insertDOList = new ArrayList<>();
            String grad = marketingDealerRatingVO.getLevel();
            MarketDealerRatingDO marketDealerRatingDO = marketDealerRatingMapper.selectByRatingIdGrad(ratingId, orgId, grad);
            String mainId;
            if (null != marketDealerRatingDO) {
                mainId = marketDealerRatingDO.getId();
            } else {
                mainId = genClient.newGuidText().getValue();
                if (StringUtils.isBlank(mainId)) {
                    throw new Exception("主键生成失败");
                }
            }

            Integer endRanking = marketingDealerRatingVO.getEndRanking();
            Integer startRanking = marketingDealerRatingVO.getStartRanking();
            scoreInfoDOMapper.updateByrRatingIdRanking(ratingId, startRanking, endRanking, grad.toUpperCase());
            List<ScoreInfoDO> scoreInfoDOList = scoreInfoDOMapper.selectByRatingIdRanking(ratingId, startRanking, endRanking);
            getMarketDealerRatingDetailDO(insertDOList, marketingDealerRatingVO, mainId, scoreInfoDOList);
            MarketDealerRatingDO record = new MarketDealerRatingDO();
            record.setId(mainId);
            record.setRatingId(ratingId);
            record.setCreateDate(new Date());
            record.setEffectiveDate(marketingDealerRatingVO.getEffectiveDate());
            record.setEndRanking(endRanking);
            record.setFailureDate(marketingDealerRatingVO.getFailureDate());
            record.setGrad(grad.toUpperCase());
            record.setOrgId(orgId);
            record.setStartRanking(startRanking);

            boolean success;
            if (null == marketDealerRatingDO) {
                success = marketDealerRatingMapper.insertSelective(record) > 0;
            } else {
                success = marketDealerRatingMapper.updateByPrimaryKeySelective(record) > 0;
            }

            if (success) {
                List<MarketingActivityVO> marketingActivityVOList =  marketingDealerRatingVO.getActivityIdList();
                ruleStrategyRelationDOMapper.delete(mainId);
                marketingActivityVOList.forEach(x->
                {
                    RuleStrategyRelationDO ruleStrategyRelationDO = new RuleStrategyRelationDO();
                    ruleStrategyRelationDO.setId(genClient.newGuidText().getValue());
                    ruleStrategyRelationDO.setRuleId(mainId);
                    ruleStrategyRelationDO.setActivityId(x.getId());
                    ruleStrategyRelationDO.setActivityName(x.getName());
                    ruleStrategyRelationDOMapper.insertSelective(ruleStrategyRelationDO);
                });

                marketDealerRatingDetailMapper.delete(mainId);
                if (!insertDOList.isEmpty()) {
                    List<MarketDealerRatingDetailDO> recordList = insertDOList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getActivityId() + "#" + o.getDealerOrgId() + "#" + o.getMainId()))), ArrayList::new));
                    marketDealerRatingDetailMapper.batchInsert(recordList);
                }

            }

        }
        return ErrorCode.Success;
    }

    private void getMarketDealerRatingDetailDO(List<MarketDealerRatingDetailDO> insertDOList, MarketingDealerRatingVO marketingDealerRatingVO, String mainId, List<ScoreInfoDO> scoreInfoDOList) throws Exception {
        for (ScoreInfoDO scoreInfoDO : scoreInfoDOList) {
            String clientId = scoreInfoDO.getClientId();
            CompanyDealerDO item = companyDealerMapper.item(Long.valueOf(clientId));
            List<MarketingActivityVO> activityIdList = marketingDealerRatingVO.getActivityIdList();
            for (MarketingActivityVO marketingActivityVO : activityIdList) {
                MarketDealerRatingDetailDO record = new MarketDealerRatingDetailDO();
                record.setDealerOrgId(item.getDealerOrgId());
                record.setDealerOrgName(item.getCompanyName());
                record.setActivityId(marketingActivityVO.getId());
                record.setActivityName(marketingActivityVO.getName());
                record.setCreateDate(new Date());
                record.setEffectiveDate(marketingDealerRatingVO.getEffectiveDate());
                record.setFailureDate(marketingDealerRatingVO.getFailureDate());
                record.setMainId(mainId);
                String id = genClient.newGuidText().getValue();
                if (StringUtils.isBlank(id)) {
                    throw new Exception("主键生成失败");
                }
                record.setId(id);
                insertDOList.add(record);
            }
        }
    }

    public List<MarketingDealerRatingVO> list(String ratingId) {
        List<MarketingDealerRatingVO> voList = new ArrayList<>();
        List<MarketDealerRatingDO> doList = marketDealerRatingMapper.selectByRatingId(ratingId);
        for (MarketDealerRatingDO marketDealerRatingDO : doList) {
            MarketingDealerRatingVO marketingDealerRatingVO = new MarketingDealerRatingVO();
            marketingDealerRatingVO.setId(marketDealerRatingDO.getId());
            marketingDealerRatingVO.setActivityIdList(ruleStrategyRelationDOMapper.selectByMainId(marketDealerRatingDO.getId()));
            marketingDealerRatingVO.setEffectiveDate(marketDealerRatingDO.getEffectiveDate());
            marketingDealerRatingVO.setFailureDate(marketDealerRatingDO.getFailureDate());
            marketingDealerRatingVO.setLevel(marketDealerRatingDO.getGrad());
            marketingDealerRatingVO.setStartRanking(marketDealerRatingDO.getStartRanking());
            marketingDealerRatingVO.setEndRanking(marketDealerRatingDO.getEndRanking());
            voList.add(marketingDealerRatingVO);
        }
        return voList;
    }

    public MarketingActivityPriceVO activityPriceModel(CompanyDealerDO companyDealerDO, String orgId, String materialsNo) {
        if (companyDealerDO == null || StringUtils.isBlank(companyDealerDO.getPriceGroup())) {
            return null;
        }
        MarketingActivityPriceVO priceInfo = marketDealerRatingDetailMapper.activityModel(companyDealerDO.getDealerOrgId(), orgId, materialsNo, companyDealerDO.getPriceGroup());
        if (null == priceInfo) {
            return null;
        }

        if (priceInfo.getModeType() == 1) {
            priceInfo.setDiscountPrice(priceInfo.getPrice());
        } else {
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                return null;
            }
            BigDecimal disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            disPrice = disPrice.multiply(priceInfo.getModeRate());
            priceInfo.setDiscountPrice(disPrice);
        }
        return priceInfo;
    }
}
